from django.contrib import admin
from .models import User

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ['username', 'user_type', 'date_joined', 'last_login']
    list_filter = ['user_type', 'date_joined']
    search_fields = ['username']
    ordering = ['-date_joined']
    
    fieldsets = (
        (None, {
            'fields': ('username', 'password')
        }),
        ('权限设置', {
            'fields': ('user_type',)
        }),
        ('个人信息', {
            'fields': ('avatar',)
        }),
    )
    
    def save_model(self, request, obj, form, change):
        """保存模型时，如果是新创建的用户且未设置密码，则设置默认密码"""
        if not change:  # 新创建
            obj.set_password('123456')  # 默认密码
        super().save_model(request, obj, form, change)
